

from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from goods.models import SPU,Brand,GoodsCategory
from meiduo_admin.serializers.spu_serializers import *
from meiduo_admin.custom_paginations import MyPage
from rest_framework.decorators import action

class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUModelSerializer
    pagination_class = MyPage


    def get_queryset(self):
        # 区分：在不同的接口视图函数中需要序列化的目标数据
        # self.get_spu_brands: Brand.objects.all()

        # 思考：如何在非视图函数中，区分此次请求所使用视图方法是什么？
        # self.action属性：代表的就是当前请求对应的视图方法名称(函数名)
        if self.action  ==  "get_spu_brands":
            return Brand.objects.all()
        return self.queryset.all()


    def get_serializer_class(self):
        # 区分：不同的视图方法，采用不同的序列化器进行操作

        # get_spu_brands视图方法使用SPUBrandModelSerializer
        if self.action == "get_spu_brands":
            return SPUBrandModelSerializer
        return self.serializer_class


    # 定义获得新增spu可选brand接口
    @action(methods=['get'], detail=False, url_path='brands/simple')
    def get_spu_brands(self, request):
        # 1、获得品牌多条模型类对象Brand
        # brand_queryset = Brand.objects.all()
        brand_queryset = self.get_queryset()

        # 2、构建品牌序列化器对象
        serializer = self.get_serializer(brand_queryset, many=True)
        # 3、序列化返回
        return Response(serializer.data)


from meiduo_admin.serializers.sku_serializers import SKUCategorySimpleSerializer
class SPUCategoryListView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = SKUCategorySimpleSerializer

    def get_queryset(self):
        # 如果接口请求的是返回一级分类  -- 请求路径没有pk  -- filter(parent=None)
        # 如果接口请求的是返回二级三级分类 -- 请求路径有pk -- filter(parent_id=pk)

        # 1、尝试获取路径中的pk
        pk = self.kwargs.get('pk')
        if not pk:
            return self.queryset.filter(parent=None)
        else:
            return self.queryset.filter(parent_id=pk)

















